using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace QLThuChi.Repositories
{
	#region using
	using QLThuChi.Models;
	#endregion
	public class KhachHangRepository
	{
		public static List<KhachHang> SelectAll()
		{
			return DataContext.Instance.KhachHangs.OrderBy(item => item.TenKhachHang).ToList();
		}

		public static KhachHang SelectByID(int makhachhang)
		{
			return DataContext.Instance.KhachHangs.FirstOrDefault(item => item.MaKhachHang == makhachhang );
		}

		public static bool Insert(KhachHang obj)
		{
			try
			{
				DataContext.Instance.KhachHangs.AddObject(obj);
				DataContext.Instance.SaveChanges();
				return true;
			}
			catch
			{
				return false;
			}
		}

		public static bool Delete(int makhachhang)
		{
			try
			{
				var delitem = DataContext.Instance.KhachHangs.FirstOrDefault(item => item.MaKhachHang == makhachhang );
				DataContext.Instance.KhachHangs.DeleteObject(delitem);
				DataContext.Instance.SaveChanges();
				return true;
			}
			catch
			{
				return false;
			}
		}

		public static bool Save()
		{
			try
			{
				DataContext.Instance.SaveChanges();
				return true;
			}
			catch
			{
				return false;
			}
		}

		public static List<KhachHang> RetrieveByID(int makhachhang)
		{
			return (from item in DataContext.Instance.KhachHangs where  item.MaKhachHang == makhachhang  select item).ToList();
		}

        public static List<KhachHang> Search(string id, string name)
        {
            var lst = new List<KhachHang>();
            foreach (var item in DataContext.Instance.KhachHangs)
            {
                if (item.MaKhachHang == (id == "" ? item.MaKhachHang : int.Parse(id)) &&
                        item.TenKhachHang.ToUpper().Contains(name == "" ? item.TenKhachHang.ToUpper() : name.Trim().ToUpper()))
                {
                    lst.Add(item);
                }
            }
            return lst;
        }
	}
}